﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

namespace RookieLibSharp.Database
{
    public class DatabaseMgr
    {

        IDatabase _Ddatabase = null;
        public DatabaseMgr(DatabaseFileType dbFileType,string dbFilePath)
        {
            InitDatabase(dbFileType, dbFilePath);
        }
        public void CloseDatabase()
        {
            _Ddatabase.CloseDatabase();
        }
        /// <summary>
        /// 返回数据库文件路径
        /// </summary>
        /// <returns></returns>
        public string GetDatabaseFilePath()
        {
            return _Ddatabase.DatabaseFilePath;
        }
        /// <summary>
        /// 初始化数据库对象
        /// </summary>
        /// <param name="databaseFileType"></param>
        public void InitDatabase(DatabaseFileType databaseFileType,string dbFilePath)
        {
            switch (databaseFileType)
            {
                case DatabaseFileType.Excel:
                    _Ddatabase = new DbExcel(dbFilePath);
                    break;
                case DatabaseFileType.Access:
                    _Ddatabase = new DbAccess(dbFilePath);
                    break;
                default:
                    _Ddatabase = null;
                    break;
            }
        }
        /// <summary>
        /// 获取全部数据
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        public DataTable GetAllData(string tableName)
        {
            CheckDatabaseFileExist(_Ddatabase.DatabaseFilePath);
            return _Ddatabase.GetAllData(tableName);
        }
        /// <summary>
        /// 执行select语句返回数据
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public DataTable ExecuteReader(string command)
        {
            return _Ddatabase.ExecuteReader(command);
        }
        /// <summary>
        /// 执行一个insert update delete操作
        /// </summary>
        /// <param name="queryString">sql语句</param>
        public int ExecuteNonQuery(string queryString)
        {
            return _Ddatabase.ExecuteNonQuery(queryString);
        }
        /// <summary>
        /// 数据文件是否存在
        /// </summary>
        /// <param name="filePath"></param>
        private void CheckDatabaseFileExist(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException();
            }
        }

    }
}
